﻿/*----------------------------------------------------------------
  //Copyright (C) 2012 赵国伟
  //文件名：DeliveryManage.cs
  //文件功能描述：快递管理
  //创建人：赵国伟
  //生成时间：2012/03/17 16:15:00
//----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Shopping.Common;
using Shopping.Model;
using Shopping.DAL;

namespace Shopping.BLL
{
    public class DeliveryManage
    {
        private readonly DALDeliveries dalDelivery = new DALDeliveries();
        private readonly DALDeliveryFees dalFee = new DALDeliveryFees();

        #region "查询指定状态下的所有快递信息 by 赵国伟 2012-04-21"
        /// <summary>
        /// 查询指定状态下的所有快递信息
        /// </summary>
        /// <param name="IsAvailable"></param>
        /// <returns></returns>
        public List<Deliveries> Query(bool IsAvailable)
        {
            string cond = "";
            if (IsAvailable) cond = "Status='" + Status.正用.ToString() + "'";
            string orderby = "OrderValue,CreateDate desc";
            return dalDelivery.QueryList(cond, orderby);
        }
        #endregion

        #region "保存一条快递信息 by 赵国伟 2012-04-21"
        /// <summary>
        /// 保存一条快递信息
        /// </summary>
        /// <param name="d"></param>
        /// <returns></returns>
        public ReturnValue Save(Deliveries d)
        {
            ReturnValue ret = new ReturnValue();
            if (dalDelivery.QueryList(1, "DeliveryName='" + d.DeliveryName + "' and DeliveryID<>" + d.DeliveryID, "") != null)
            {
                ret.Message = "快递名称重复！";
                return ret;
            }
            d.CreateDate = DateTime.Now;
            d.LastModifyDate = DateTime.Now;
            if (d.DeliveryID <= 0)
            {
                if (dalDelivery.Add(d) > 0)
                {
                    ret.Result = ResultType.Success;
                    ret.Message = "保存成功！";
                }
            }
            else
            {
                Deliveries o = dalDelivery.GetModel(d.DeliveryID);
                d.CreateDate = o.CreateDate;
                if (dalDelivery.Update(d) > 0)
                {
                    ret.Result = ResultType.Success;
                    ret.Message = "保存成功！";
                }
            }
            return ret;
        }
        #endregion

        #region "查询一条快递信息；by 赵国伟 2012-04-21"
        /// <summary>
        /// 查询一条快递信息；
        /// </summary>
        /// <param name="DeliveryID"></param>
        /// <returns></returns>
        public Deliveries Get(int DeliveryID)
        {
            return dalDelivery.GetModel(DeliveryID);
        }
        #endregion

        #region "删除一条快递信息；by 赵国伟 2012-04-21"
        /// <summary>
        /// 删除一条快递信息；
        /// </summary>
        /// <param name="DeliveryID"></param>
        /// <returns></returns>
        public ReturnValue Delete(int DeliveryID)
        {
            ReturnValue ret = new ReturnValue();
            if (dalDelivery.Delete(DeliveryID) > 0)
            {
                ret.Result = ResultType.Success;
                ret.Message = "删除成功！";
            }
            return ret;
        }
        #endregion

        #region "查询快递方式并输出为下拉选项。by 赵国伟 2012-04-21"
        /// <summary>
        /// 查询快递方式并输出为下拉选项。
        /// </summary>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static string QueryDeliveryToSelectOption(string defaultValue)
        {
            List<IDNameObj> datas = DALHelper.QueryIDNameObjs<Deliveries>("", DeliveriesEnum.DeliveryName);
            StringBuilder sb = new StringBuilder(500);
            if (datas != null)
            {
                foreach (IDNameObj datainfo in datas)
                {
                    sb.Append("<option value=\"");
                    sb.Append(datainfo.Name);
                    sb.Append("\" ");
                    if (defaultValue == datainfo.Name.ToString())
                        sb.Append(" Selected ");
                    sb.Append(">");
                    sb.Append(datainfo.Name);
                    sb.Append("</option>");
                }
            }
            return sb.ToString();
        }
        #endregion

        #region "删除一条指定的快递费用设置； by 赵国伟 2012-04-21"
        /// <summary>
        /// 删除一条指定的快递费用设置；
        /// </summary>
        /// <param name="DeliveryFeesID"></param>
        /// <returns></returns>
        public ReturnValue DeleteDeliveryFee(int DeliveryFeesID)
        {
            ReturnValue ret = new ReturnValue();
            if (dalFee.Delete(DeliveryFeesID) > 0)
            {
                ret.Message = "删除成功！";
                ret.Result = ResultType.Success;
            }
            return ret;
        }
        #endregion

        #region "分页查询快递费用设置信息；by 赵国伟 2012-04-22"
        /// <summary>
        /// 分页查询快递费用设置信息；
        /// </summary>
        /// <param name="q"></param>
        /// <returns></returns>
        public List<DeliveryFeeInfo> QueryDeliveryFeeAsPage(QueryDeliveryFeeAsPage q)
        {
            string cond = "1=1 ";
            if (q.DeliveryID > 0) cond += " and DeliveryID=" + q.DeliveryID;
            if (q.AreaID > 0)
                cond += " and AreaID=" + q.AreaID;
            else
            {
                if (q.CityID > 0)
                    cond += " and AreaID in(Select AreaID From Areas where CityID=" + q.CityID + ")";
                else
                {
                    if (q.ProvinceID > 0)
                        cond += " and AreaID in(Select AreaID From Areas Where CityID in(Select CityID From Cities Where ProvinceID=" + q.ProvinceID + "))";
                }
            }

            string orderby = "CreateDate desc ";
            List<DeliveryFees> listOfS = dalFee.QueryListAsPage(cond, orderby, q.CurPage, q.PageSize, out q.TotalCount);
            List<DeliveryFeeInfo> listOfT = null;
            if (listOfS != null)
            {
                listOfT = new List<DeliveryFeeInfo>();
                Dictionary<int, string> dictDelivery = BLLHelper.GenerateToHash<Deliveries>("", DeliveriesEnum.DeliveryName);
                Dictionary<int, AreaCityProvinceInfo> dictArea = DALAreas.QueryAreaCityProvinceToHash("AreaID in(Select AreaID from DeliveryFees where " + cond + ")", "");
                foreach (DeliveryFees s in listOfS)
                {
                    DeliveryFeeInfo t = new DeliveryFeeInfo();
                    t.Fee = s;
                    t.DeliveryName = dictDelivery[s.DeliveryID];
                    t.AreaName = dictArea[s.AreaID].AreaName;
                    t.City = new IDNameObj();
                    t.City.ID = dictArea[s.AreaID].CityID;
                    t.City.Name = dictArea[s.AreaID].CityName;
                    t.Province = new IDNameObj();
                    t.Province.ID = dictArea[s.AreaID].ProvinceID;
                    t.Province.Name = dictArea[s.AreaID].ProvinceName;
                    listOfT.Add(t);
                }
            }
            return listOfT;
        }
        #endregion

        #region "查询一条快递费设置信息； by 赵国伟 2012-04-22"
        /// <summary>
        /// 查询一条快递费设置信息；
        /// </summary>
        /// <param name="DeliveryFeesID"></param>
        /// <returns></returns>
        public DeliveryFeeInfo GetDeliveryFee(int DeliveryFeesID)
        {
            DeliveryFees s = dalFee.GetModel(DeliveryFeesID);
            DeliveryFeeInfo t = null;
            if (s != null)
            {
                t = new DeliveryFeeInfo();
                t.Fee = s;
                t.DeliveryName = DALHelper.GetFieldValue<Deliveries>(s.DeliveryID, DeliveriesEnum.DeliveryName.ToString());
                Dictionary<int, AreaCityProvinceInfo> dictArea = DALAreas.QueryAreaCityProvinceToHash("AreaID=" + s.AreaID, "");
                t.AreaName = dictArea[s.AreaID].AreaName;
                t.City = new IDNameObj();
                t.City.ID = dictArea[s.AreaID].CityID;
                t.City.Name = dictArea[s.AreaID].CityName;
                t.Province = new IDNameObj();
                t.Province.ID = dictArea[s.AreaID].ProvinceID;
                t.Province.Name = dictArea[s.AreaID].ProvinceName;
            }
            return t;
        }
        #endregion

        #region "保存一条快递费用设置信息； by 赵国伟 2012-04-22"
        /// <summary>
        /// 保存一条快递费用设置信息；
        /// </summary>
        /// <param name="d"></param>
        /// <param name="areaIds"></param>
        /// <returns></returns>
        public ReturnValue SaveDeliveryFee(DeliveryFees d, List<int> areaIds)
        {
            ReturnValue ret = new ReturnValue();
            d.CreateDate = DateTime.Now;
            if (d.DeliveryFeesID > 0)
            {
                if (dalFee.Update(d) > 0)
                {
                    ret.Result = ResultType.Success;
                    ret.Message = "保存成功！";
                }
            }
            else
            {
                List<DeliveryFees> listOfData = new List<DeliveryFees>();

                //判断是否重复添加；
                string cond = "DeliveryID=" + d.DeliveryID;
                List<string> ids = Utility.IntArrayToStringArray(areaIds);
                cond += " and AreaID in('" + string.Join("','", ids.ToArray()) + "')";
                if (dalFee.QueryList(1, cond, "") != null)
                {
                    ret.Message = "本次添加的快递费区域重复，请检查！";
                    return ret;
                }
                foreach (int areaId in areaIds)
                {
                    DeliveryFees t = dalFee.Copy(d);
                    t.AreaID = areaId;
                    listOfData.Add(t);
                }
                //开始批量添加保存；
                ret = dalFee.BatchAdd(listOfData);
            }
            return ret;
        }
        #endregion

        #region "查询指定快递在指定区域的快递费设置； by 赵国伟 2012-08-20"
        /// <summary>
        /// 查询指定快递在指定区域的快递费设置；
        /// </summary>
        /// <param name="deliveryID"></param>
        /// <param name="areaId"></param>
        /// <returns></returns>
        public DeliveryFees GetDeliveryFee(int deliveryID, int areaId)
        {
            return dalFee.GetDeliveryFee(deliveryID, areaId);
        }
        #endregion


        #region "计算运费 by 赵国伟 2012-08-20"
        /// <summary>
        /// 计算运费
        /// </summary>
        /// <param name="deliveryID"></param>
        /// <param name="areaId"></param>
        /// <param name="totalWeight"></param>
        /// <returns></returns>
        public decimal ComputeSendFee(int deliveryID,int areaId, int totalWeight)
        {
            decimal fee = 0.00M;

            if (deliveryID <= 0 )
                return fee;

            Deliveries d = Get(deliveryID);
            DeliveryFees df = GetDeliveryFee(deliveryID, areaId);

            int firstWeight = 0, perWeight = 0;
            decimal firstWeightFee = 0.00M, perWeightFee = 0.00M;
            if (df != null)
            {
                firstWeight = df.FirstWeight;
                firstWeightFee = df.FirstWeightFee;
                perWeight = df.PerWeight;
                perWeightFee = df.PerWeightFee;
            }
            else
            {
                firstWeight = d.FirstWeight;
                firstWeightFee = d.FirstWeightFee;
                perWeight = d.PerWeight;
                perWeightFee = d.PerWeightFee;
            }
            if (totalWeight <= firstWeight)
                fee = firstWeightFee;
            else
                fee = firstWeightFee + Utility.Cast2int(totalWeight - firstWeight) / perWeight * perWeightFee;
            return Math.Round(fee, 2);
        }
        #endregion



    }
}
